import UIKit

// Toast
class Toast: UITextView {
    private static let BACKGROUND_COLOR = UIColor(red: 96 / 255,
        green: 96 / 255, blue: 96 / 255, alpha: 0.8)    // 背景色
    private static let CORNER_RADIUS: CGFloat = 10      // 圆角半径
    public static let LENGTH_LONG: TimeInterval = 3.5   // 长停留时间，单位秒
    public static let LENGTH_SHORT: TimeInterval = 2    // 短停留时间，单位秒
    private let mTimerInit: TimeInterval = 0.5          // 定时器时间间隔，单位秒
    private var mDuration: TimeInterval!                // 停留时间
    private var mParent: UIView!                        // 父视图
    private var mPassed: TimeInterval!                  // 已消耗时间
    private var mTimer: Timer!                          // 定时器

    /**
     * 创建 Toast。
     * @param parent    父视图
     * @param text      显示的文字
     * @param duration  停留时间
     * @return Toast
     */
    public static func makeText(_ parent: UIView, text: String, duration: TimeInterval) -> Toast {
        var newText = text
        let toast = Toast()
        toast.mDuration = duration
        toast.mParent = parent
        toast.mPassed = 0

        let screenWidth = UIScreen.main.bounds.width
        let screenHeight = UIScreen.main.bounds.height
        let fontSize = screenHeight > screenWidth ? screenHeight / 40: screenWidth / 40

        // 设置尺寸和位置
        var width = CGFloat(text.count + 2) * fontSize
        var height = 3 * fontSize
        let lines = Int(width / screenWidth) + 1
        
        // 如果文字过长，就添加换行符
        if lines > 1 {
            let indexBase = text.count / lines + 2
            width = CGFloat(indexBase) * fontSize
            for i in 1 ..< lines {
                let index = indexBase * i
                let insertIndex = newText.index(newText.startIndex, offsetBy: index)
                newText.insert("\n", at: insertIndex)
            }
            height = height + CGFloat(lines) * fontSize
        }

        let x = (screenWidth - width) / 2
        let y = screenHeight / 3 * 2
        toast.frame = CGRect(x: x, y: y, width: width, height: height)

        // 设置字体
        toast.font = UIFont.systemFont(ofSize: fontSize)

        // 设置显示的文字
        toast.text = text
        
        // 设置圆角半径
        toast.layer.cornerRadius = Toast.CORNER_RADIUS
        
        // 设置背景色
        toast.backgroundColor = Toast.BACKGROUND_COLOR
        
        // 设置文字颜色
        toast.textColor = UIColor.white
        
        // 设置文字居中
        toast.textAlignment = NSTextAlignment.center
        let vInset = (height - toast.contentSize.height) / 2
        toast.contentInset.top = vInset
        toast.contentInset.bottom = vInset
        
        return toast
    }

    /**
     * 定时器事件的响应方法。
     */
    @objc public func onTimer() {
        if mPassed < mDuration {
            // 继续计时
            mPassed += mTimerInit
        } else {
            // 结束计时，并从父视图中移除
            mTimer.invalidate()
            super.removeFromSuperview()
        }
    }

    /**
     * 显示。
     */
    public func show() {
        // 添加到父视图
        mParent.addSubview(self)
        
        // 在所有子视图前面
        mParent.bringSubviewToFront(self)
        
        // 开始计时
        mTimer = Timer.scheduledTimer(timeInterval: mTimerInit, target: self, selector: #selector(Toast.onTimer), userInfo: nil, repeats: true)
    }
}
